$(document).ready(function () {
    /* 词汇查询接口实例 */
    var editor1 = ace.edit("editorReq1");
    editor1.setTheme("ace/theme/clouds");
    editor1.session.setMode("ace/mode/javascript");

    var editor2 = ace.edit("editorRes1");
    editor2.setTheme("ace/theme/clouds");
    editor2.session.setMode("ace/mode/javascript");

    /* 批量音标标注实例 */
    var editor3 = ace.edit("editorReq2");
    editor3.setTheme("ace/theme/clouds");
    editor3.session.setMode("ace/mode/text");

    var editor4 = ace.edit("editorRes2");
    editor4.setTheme("ace/theme/clouds");
    editor4.session.setMode("ace/mode/javascript");

    /* 超纲词检测实例 */
    var editor5 = ace.edit("editorReq3");
    editor5.setTheme("ace/theme/clouds");
    editor5.session.setMode("ace/mode/javascript");

    var editor6 = ace.edit("editorRes3");
    editor6.setTheme("ace/theme/clouds");
    editor6.session.setMode("ace/mode/javascript");

    editor1.session.setValue("$.ajax('/search',{\n  method: 'post',\n  data:{\n    " +
        "segment: 'test',\n    scales: '1,2,3',\n    type: 'detail'\n  }\n})");

    editor3.session.setValue('Mark phonetic for this paragraph.\nHere is another line.');

    editor5.session.setValue("$.ajax('/filterScale',{\n  method: 'post',\n  data:{\n    " +
        "text: 'if there are words not belong to junior high school?',\n    scale: '2'\n  }\n})");

    emitExample();emitOutScaleExample();emitPhoneticExample();

    editor1.session.on('change', debounce(800, emitExample));
    editor3.session.on('change', debounce(300, emitPhoneticExample));
    editor5.session.on('change', debounce(800, emitOutScaleExample));

    function emitExample() {
        try {
            var ajax = eval(editor1.session.getValue());
            if (ajax && ajax.done && ajax.fail) {
                ajax.done(function (data, status, xhr) {
                    editor2.session.setValue('/*\n' + xhr.getAllResponseHeaders() + '*/\n\n' + formatJson(data));
                }).fail(function () {
                    editor2.session.setValue("");
                });
            }
        } catch (e) {
            editor2.session.setValue("");
        }
    }

    function emitPhoneticExample() {
        $.post('/phonetic', {
            text: editor3.session.getValue()
        }, function (data, status, xhr) {
            editor4.session.setValue('/*\n' + xhr.getAllResponseHeaders() + '*/\n\n' + formatJson(data));
        });
    }

    function emitOutScaleExample() {
        try {
            var ajax = eval(editor5.session.getValue());
            if (ajax && ajax.done && ajax.fail) {
                ajax.done(function (data, status, xhr) {
                    editor6.session.setValue('/*\n' + xhr.getAllResponseHeaders() + '*/\n\n' + formatJson(data));
                }).fail(function () {
                    editor6.session.setValue("");
                });
            }
        } catch (e) {
            editor6.session.setValue("");
        }
    }
});